package com.litchi.tutor.common.config.web;

import com.litchi.tutor.common.config.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.TimeUnit;

/**
 * @author hoby
 * @since 2021-08-22
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${savePath:/data/springboot-demo/file/}")
    private String savePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/media/**")
                .addResourceLocations("file:" + savePath)
                .setCacheControl(CacheControl.maxAge(864000, TimeUnit.SECONDS).cachePublic());
    }

    /**
     * 拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor())//添加拦截器
                .excludePathPatterns("/test","/user/loginByCode", "/user/loginByOpenId", "/staff/**" ,"/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**")
                .addPathPatterns("/**"); //拦截所有请求
    }

    /**
     * 自己写的拦截器
     * @return
     */
    @Bean
    public LoginInterceptor loginInterceptor() {
         return new LoginInterceptor();
     }
}
